package cn.yuxiaoyuan.user.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import cn.yuxiaoyuan.base.service.impl.BaseServiceImpl;
import cn.yuxiaoyuan.system.domain.Logininfo;
import cn.yuxiaoyuan.system.mapper.LogininfoMapper;
import cn.yuxiaoyuan.user.domain.User;
import cn.yuxiaoyuan.user.mapper.UserMapper;
import cn.yuxiaoyuan.user.query.UserQuery;
import cn.yuxiaoyuan.user.service.UserService;
import com.alibaba.druid.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Override
    @Transactional
    public void add(User user) {
        //验证
        if(StringUtils.isEmpty(user.getUserName())){
           throw new RuntimeException("用户名不能为空");
        }
        if(StringUtils.isEmpty(user.getPhone())){
            throw new RuntimeException("手机号不能为空");
        }
        if(StringUtils.isEmpty(user.getPassword())){
            throw new RuntimeException("密码不能为空");
        }
        //生成一个盐值
        String salt = RandomUtil.randomString(32);
        //你要对什么进行加密  md5是不可逆
        user.setSalt(salt);
        String pwd = SecureUtil.md5(user.getPassword()+salt);
        user.setPassword(pwd);

        Logininfo logininfo = new Logininfo();
        logininfo.setSalt(salt);
        logininfo.setPassword(pwd);
        logininfo.setEmail(user.getEmail());
        logininfo.setPhone(user.getPhone());
        logininfo.setType(1);
        logininfo.setDisable(1);
        logininfo.setUsername(user.getUserName());
        logininfoMapper.add(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
    }

    @Override
    public List<User> queryPage(UserQuery query) {
        return userMapper.queryPage(query);
    }
}
